package com.tjetc.common.timing;

import com.tjetc.dao.DailyAmountMapper;
import com.tjetc.dao.MonthlyAmountMapper;
import com.tjetc.entity.*;
import com.tjetc.service.AdminService;
import com.tjetc.service.MerchantService;
import com.tjetc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/* 定时任务，定时计算每日的商家的总销售额和月结算 */

@Component
public class CountDailyAmount {
    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private DailyAmountMapper dailyAmountMapper;

    @Autowired
    private MonthlyAmountMapper monthlyAmountMapper;

    @Autowired
    private AdminService adminService;

    @Transactional
    @Scheduled(cron = "1 0 0 * * ?")
    public void dailyTask() {
        // 在每日的24点执行的任务 日结算，收入支出明细存表格
        LocalDateTime currentTime = LocalDateTime.now().minusDays(1);
        // 查询当天时间是否已经存在订单，如果存在订单先进行删除
        dailyAmountMapper.deleteByTime(currentTime);
        // 获取管理员
        List<Admin> admins = adminService.listAll();
        // 获取当前所有商家
        List<Merchant> merchants = merchantService.selectAllMerchant();
        for(Merchant itemMerchant : merchants) {
            // 获取今日订单
            List<Order> dailyOrders = orderService.getOrderByDayTime(currentTime, itemMerchant.getId());
            Integer finishOrderNumber = 0;
            Integer canceledOrderNumber = 0;
            BigDecimal amount = new BigDecimal(0);
            for(Order itemOrder : dailyOrders) {
                // 只有已完成：3是待评价订单，4是已经评价的完成的订单
                if(itemOrder.getStatus() == 3 || itemOrder.getStatus() == 4) {
                    amount = amount.add(itemOrder.getAmount());
                    finishOrderNumber ++;
                } else if(itemOrder.getStatus() == -1 || itemOrder.getStatus() == -2) {
                    // 取消的订单 -1和-2
                    canceledOrderNumber ++;
                }
            }
            // 平台抽成
            BigDecimal adminAmount = amount.multiply(itemMerchant.getCommission());
            // 商家收益
            BigDecimal merchantAmount = amount.subtract(adminAmount);
            // 存储抽成
            BigDecimal commission = itemMerchant.getCommission();
            // 调用insert
            DailyAmount dailyAmount = new DailyAmount();
            dailyAmount.setAmount(amount);
            dailyAmount.setAdminAmount(adminAmount);
            dailyAmount.setMerchantAmount(merchantAmount);
            dailyAmount.setCommission(commission);
            dailyAmount.setCanceledOrderNumber(canceledOrderNumber);
            dailyAmount.setFinishOrderNumber(finishOrderNumber);
            dailyAmount.setMerchantId(itemMerchant.getId());
            dailyAmount.setTime(currentTime);
            dailyAmountMapper.insertDailyAmount(dailyAmount);
        }
    }

    @Transactional
    @Scheduled(cron = "1 0 0 1 * ?")
    public void monthlyTask() {
        // 在每月的月初执行的任务 月结算，收入支出明细存表格，计算总数，发钱（不是实际的发，而是直接转到商家的数据库中）
        // 取得上个月
        LocalDateTime currentTime = LocalDateTime.now().minusMonths(-1);
        // 删除重复
        Integer deleteLong = monthlyAmountMapper.deleteByTime(currentTime);
        // 获取管理员
        Admin admin = adminService.listAll().get(0);
        // 获取当前商家
        List<Merchant> merchants = merchantService.selectAllMerchant();
        // 遍历每个商家
        for(Merchant itemMerchant : merchants) {
            // 获取当月每日的总结
            List<DailyAmount> dailyAmounts = dailyAmountMapper.selectByMonthTime(currentTime, itemMerchant.getId());
            // 月总收入
            BigDecimal amount = new BigDecimal(0);
            // 月admin总收入
            BigDecimal adminAmount = new BigDecimal(0);
            // 月merchant总收入
            BigDecimal merchantAmount = new BigDecimal(0);
            // 完成和取消的订单数量
            Integer finishOrderNumber = 0;
            Integer canceledOrderNumber = 0;
            // 遍历这个月每天的记录
            for(DailyAmount dailyAmount : dailyAmounts) {
                amount = amount.add(dailyAmount.getAmount());
                adminAmount = adminAmount.add(dailyAmount.getAdminAmount());
                merchantAmount = merchantAmount.add(dailyAmount.getMerchantAmount());
                finishOrderNumber += dailyAmount.getFinishOrderNumber();
                canceledOrderNumber += dailyAmount.getCanceledOrderNumber();
            }
            MonthlyAmount monthlyAmount = new MonthlyAmount();
            monthlyAmount.setAdminAmount(adminAmount);
            monthlyAmount.setMerchantAmount(merchantAmount);
            monthlyAmount.setTime(currentTime);
            monthlyAmount.setMerchantId(itemMerchant.getId());
            monthlyAmount.setAmount(amount);
            monthlyAmount.setFinishOrderNumber(finishOrderNumber);
            monthlyAmount.setCanceledOrderNumber(canceledOrderNumber);
            monthlyAmountMapper.insertMonthlyAmount(monthlyAmount);
            admin.setAmount(admin.getAmount().subtract(merchantAmount));
            itemMerchant.setAmount(itemMerchant.getAmount().add(merchantAmount));
        }
    }
}
